package org.feng.support.impl;

import cn.hutool.core.io.file.FileNameUtil;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.feng.entity.PubResource;
import org.feng.entity.result.UploadResult;
import org.feng.support.UploadInterface;
import org.feng.support.proxy.ProxyUpload;
import org.feng.utils.UploadFileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * qiniu
 *
 * @author : FengShuai
 * @since : 2024/6/27 9:24
 */
public class QiNiu implements UploadInterface {
    private PubResource pubResource;
    private Auth auth;
    private UploadManager uploadManager;

    public QiNiu(PubResource pubResource) {
        Configuration cfg = new Configuration(Region.autoRegion());
        this.uploadManager = new UploadManager(cfg);
        this.pubResource = pubResource;
        this.auth = Auth.create(pubResource.getKey(), pubResource.getSecret());
    }

    @Override
    public UploadResult putFile(MultipartFile file) {
        UploadResult uploadResult = ProxyUpload.checkMd5(file);
        if (uploadResult.getFileUrl() != null) {
            return uploadResult;
        }
        String fileName = UploadFileUtils.getFileName(file.getOriginalFilename());
        String token = auth.uploadToken(pubResource.getBucket());
        try {
            uploadManager.put(file.getInputStream(), fileName, token, null, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        uploadResult = new UploadResult();
        uploadResult.setFileName(file.getOriginalFilename());
        uploadResult.setFileUrl(getFileLink(fileName));
        uploadResult.setFileSize(file.getSize());
        uploadResult.setFileType(FileNameUtil.extName(file.getOriginalFilename()));
        uploadResult.setFileMd5(uploadResult.getFileMd5());
        ProxyUpload.saveMd5(uploadResult);
        return uploadResult;
    }

    private String getFileLink(String fileName) {
        return this.pubResource.getEndpoint() + "/" + fileName;
    }
}
